package org.example.Utils;

import org.example.POJO.online.MyMessage;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketUtil {
    //创建socket
    public static Socket create(String ip,int port) throws IOException {
        try{
            Socket socket = new Socket(InetAddress.getByName(ip),port);
            return socket;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    public static Socket createLocalHost(int port) throws IOException {
        try{
            Socket socket = new Socket(InetAddress.getLocalHost(),port);
            return socket;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    public static void send(Socket socket, MyMessage myMessage) throws IOException {
        OutputStream os = null;
        ObjectOutputStream oos = null;
        try {
            os = socket.getOutputStream();
            oos = new ObjectOutputStream(os);
            oos.writeObject(myMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static MyMessage receive(Socket socket) throws IOException {
        InputStream is = null;
        ObjectInputStream ois = null;
        try {
            is = socket.getInputStream();
            ois = new ObjectInputStream(is);
            return (MyMessage) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    public static void close(InputStream is, OutputStream os,Socket socket) throws IOException {
        if (is != null) {
            try {
                is.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (os != null) {
            try {
                os.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            if (socket != null) {
                try {
                    socket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
